package com.ken.astroboy.quartz;

import java.io.IOException;

import com.ken.astroboy.core.InMemoryStorage;
import com.ken.astroboy.model.ScheduledTaskCustomData;
import com.ken.astroboy.service.WxService;
import com.ken.astroboy.util.Exceptions;

public class CommonJob extends AbstractJob{

	@Override
	void doJob(ScheduledTaskCustomData customData) throws IOException {
		
		int i = 0;
		int limit = 32;
		int pauseTime = 30000;
		
		for(String group : customData.getGroupReceivers()){
		
			if(InMemoryStorage.userGroupCtrlEntity.getGroupList().contains(group)){
				
				if(i >= limit){
					logger.info("已发送目标数等于{}，休眠{}ms再继续发送", i, pauseTime);
					i = 0;
					try {
						Thread.sleep(pauseTime);
					} catch (InterruptedException e) {
						logger.info(Exceptions.getExceptionDetail(e));
					}
				}else{
					i++;
				}
				
				String userName = null;
				if(InMemoryStorage.groupMap.get(group) != null){
					userName = InMemoryStorage.groupMap.get(group).getUserName();
				}
				
				if(userName == null){
					continue;
				}
				
				for(String text : customData.getTextList()){					
					WxService.sendTextMsg( text, userName );
				}

				for(String image : customData.getImageList()){
					WxService.sendImgMsg( image, userName );
				}
			}
			
		}
		
		for(String friend : customData.getFriendReceivers()){
			
			if(i >= limit){
				logger.info("已发送目标数等于{}，休眠{}ms再继续发送", i, pauseTime);
				i = 0;
				try {
					Thread.sleep(pauseTime);
				} catch (InterruptedException e) {
					logger.info(Exceptions.getExceptionDetail(e));
				}
			}else{
				i++;
			}
			
			String userName = null;
			if(InMemoryStorage.friendMap.get(friend) != null){
				userName = InMemoryStorage.friendMap.get(friend).getUserName();
			}
			
			if(userName == null){
				continue;
			}
			
			for(String text : customData.getTextList()){
				WxService.sendTextMsg( text, userName );
			}

			for(String image : customData.getImageList()){
				WxService.sendImgMsg( image, userName );
			}
			
		}		
	}
}
